import request from './request'

// 地址接口类型定义
export interface Address {
  id: number
  userId: number
  receiverName: string
  receiverPhone: string
  province: string
  city: string
  district: string
  address: string
  fullAddress: string
  postalCode?: string
  isDefault: 0 | 1
  isDefaultText: string
  createdAt: string
  updatedAt: string
}

export interface CreateAddressRequest {
  receiverName: string
  receiverPhone: string
  province: string
  city: string
  district: string
  address: string
  postalCode?: string
  isDefault?: 0 | 1
}

export interface UpdateAddressRequest {
  receiverName?: string
  receiverPhone?: string
  province?: string
  city?: string
  district?: string
  address?: string
  postalCode?: string
  isDefault?: 0 | 1
}

// 地址API
export const addressApi = {
  // 获取用户地址列表
  getUserAddresses(userId: number): Promise<{ data: Address[] }> {
    return request.get(`/api/users/${userId}/addresses`)
  },

  // 创建地址
  createAddress(userId: number, data: CreateAddressRequest): Promise<{ data: Address }> {
    return request.post(`/api/users/${userId}/addresses`, data)
  },

  // 更新地址
  updateAddress(userId: number, addressId: number, data: UpdateAddressRequest): Promise<{ data: Address }> {
    return request.put(`/api/users/${userId}/addresses/${addressId}`, data)
  },

  // 删除地址
  deleteAddress(userId: number, addressId: number): Promise<{ data: null }> {
    return request.delete(`/api/users/${userId}/addresses/${addressId}`)
  },

  // 设置默认地址
  setDefaultAddress(userId: number, addressId: number): Promise<{ data: Address }> {
    return request.patch(`/api/users/${userId}/addresses/${addressId}/default`)
  },

  // 获取默认地址
  getDefaultAddress(userId: number): Promise<{ data: Address | null }> {
    return this.getUserAddresses(userId).then(res => {
      const defaultAddress = res.data.find(addr => addr.isDefault === 1)
      return { data: defaultAddress || null }
    })
  }
}
